package ruifight.member.config;
 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import ruifight.member.model.UserInfo;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
 
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
 
        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }
 
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
 
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
 
    }
 
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null) {
        	try {
	            Claims claims = Jwts.parser()
	                    .setSigningKey("ruifight")
	                    .parseClaimsJws(token.replace("Bearer ", ""))
	                    .getBody();
	            String loginName=(String) claims.get("loginName");
	            String password=(String) claims.get("password");
	            UserInfo userInfo = new UserInfo();
	            userInfo.setLoginName(loginName);
	            userInfo.setPassword(password);
	            if (loginName != null) {
	                return new UsernamePasswordAuthenticationToken(loginName, userInfo);
	            }
        	} catch (SignatureException | MalformedJwtException e) {
                // jwt 解析错误
            } catch (ExpiredJwtException e) {
                // jwt 已经过期，在设置jwt的时候如果设置了过期时间，这里会自动判断jwt是否已经过期，如果过期则会抛出这个异常，我们可以抓住这个异常并作相关处理。
            }
            return null;
        }
        return null;
    }
}
